package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.po.Clazz;
import com.itheima.domain.vo.PageResult;
import com.itheima.mapper.ClazzMapper;
import com.itheima.service.ClazzService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Override
    public PageResult list(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        //校验参数
        if (page <= 0 || pageSize <= 0) {
            throw new RuntimeException("参数错误");
        }
        Page<Clazz> clazzPage = Page.of(page, pageSize);
//        QueryWrapper<Clazz> clazzQueryWrapper = new QueryWrapper<Clazz>()
//                .like(StringUtils.isNotBlank(name), "name", name)
//                .between(begin != null && end != null && begin.isBefore(end), "begin", begin, end)
//                .orderByDesc("update_time");
//        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<Clazz>()
//                .like(StringUtils.isNotBlank(name), Clazz::getName, name)
//                .between(begin != null && end != null && begin.isBefore(end), Clazz::getBeginDate, begin, end)
//                .orderByDesc(Clazz::getUpdateTime);
//        this.page(clazzPage, queryWrapper);
        this.lambdaQuery()
                .like(StringUtils.isNotBlank(name), Clazz::getName, name)
                .between(begin != null && end != null && begin.isBefore(end), Clazz::getBeginDate, begin, end)
                .orderByDesc(Clazz::getUpdateTime)
                .page(clazzPage);
        List<Clazz> records = clazzPage.getRecords();
        if (records == null) throw new RuntimeException("没有查询到数据");
        records.forEach(clazz -> {
            LocalDate Now = LocalDate.now();
            clazz.setMasterName(clazz.getMasterId() != null ? clazz.getMasterId().toString() : "");
            clazz.setStatus(Now.isBefore(clazz.getBeginDate()) ? "未开始" : Now.isAfter(clazz.getEndDate()) ? "已结束" : "进行中");
        });
        return new PageResult(clazzPage.getTotal(), records);
    }

    @Override
    public void saveClazz(Clazz clazz) {
//        clazz.setCreateTime(LocalDateTime.now());
//        clazz.setUpdateTime(LocalDateTime.now());
        this.save(clazz);
    }

    @Override
    public void updateClazzById(Clazz clazz) {
//        clazz.setUpdateTime(LocalDateTime.now());
        this.updateById(clazz);
    }
}
